package com.nanychuan.blogbase.utils;

import com.nanychuan.blogback.pojo.User;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 往
 * 上传文件工具类
 */
public class UploadFileUtil {
    public static Map<String,Object> fileUpload(@RequestParam(value = "editormd-image-file",required = false) MultipartFile img,
                                                HttpSession session){
        //将上传成功的图片保存到upload目录下
        String realPath = session.getServletContext().getRealPath("/upload");
        //拼接子目录
        realPath += File.separator + DateTimeUtil.getDate();
        //获取当前登录的用户名再次拼接
        User user = (User) session.getAttribute("user");
        realPath += File.separator + user.getUsername();
        //创建文件
        File file = new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        //解决同一用户上传相同的文件
        String fileName = img.getOriginalFilename();
        //拼接当前日期的毫秒值
        fileName = System.currentTimeMillis() + fileName;
        //定义map集合返回给editorMd回显数据
        Map<String,Object> map = new HashMap<>();
        //获取回调地址
        String url = "http://localhost:8085/upload/"+ DateTimeUtil.getDate()+
                File.separator+user.getUsername()+File.separator+fileName;
        try {
            //保存图片
            img.transferTo(new File(realPath+File.separator+fileName));
            //返回执行结果
            map.put("success",1);
            //返回回调地址
            map.put("url",url);
            //返回图片上传成功的message
            map.put("message","图片上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;

    }
}
